﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Enter.Common
{
	public static class Extensions
	{
		#region To T

		/// <summary>
		/// 将字符转换成自己的类型
		/// </summary>
		/// <param name="val">System.String</param>
		/// <returns>如果转换失败将返回 T 的默认值</returns>
		public static T To<T>(this object val)
		{
			if (val != null)
			{
				return val.To<T>(default(T));
			}
			else
			{
				return default(T);
			}
		}
		/// <summary>
		/// 将字符转换成自己的类型
		/// </summary>
		/// <param name="val">System.Object</param>
		/// <param name="defVal">在转换成 T 失败时，返回的默认值</param>
		/// <returns>类型 T 的值</returns>
		public static T To<T>(this object val, T defVal)
		{
			if (val == null)
				return (T)defVal;
			if (val is T)
				return (T)val;

			Type type = typeof(T);
			try
			{
				if (type.BaseType == typeof(Enum))
				{
					return (T)Enum.Parse(type, val.ToString(), true);
				}
				else
				{
					return (T)Convert.ChangeType(val, type);
				}
			}
			catch
			{
				return defVal;
			}
		}

		#endregion
	}
}
